package com.kasax.ipcbus.corel.marker;

import com.kasax.ipcbus.bean.Request;
import com.kasax.ipcbus.bean.RequestBean;
import com.kasax.ipcbus.bean.RequestParameter;
import com.kasax.ipcbus.bean.Response;
import com.kasax.ipcbus.bean.ResponseBean;
import com.kasax.ipcbus.corel.ObjectCenter;
import com.kasax.ipcbus.corel.TypeCenter;
import com.kasax.ipcbus.utils.GsonUtils;
import com.kasax.ipcbus.utils.LogUtils;

public abstract class ResponseMaker {
    protected TypeCenter typeCenter = TypeCenter.getInstance();
    protected ObjectCenter OBJ_CENTER = ObjectCenter.getInstance();
    // 返回结果的类型
    protected Class<?> resultClass;

    // 参数
    protected Object[] mParameters;

    public Response makeResponse(Request request) {
        LogUtils.i(getClass(), "makeResponse request: " + GsonUtils.toJson(request));
        // 参数还原
        String requestData = request.getData();
        RequestBean requestBean = GsonUtils.fromJson(requestData, RequestBean.class);
        resultClass = typeCenter.getClassType(requestBean.getResultClsName());
        // 参数还原
        RequestParameter[] parameters = requestBean.getRequestParameters();
        if (parameters != null && parameters.length > 0) {
            mParameters = new Object[parameters.length];
            for (int i = 0; i < parameters.length; i++) {
                RequestParameter param = parameters[i];
                Class clazz = typeCenter.getClassType(param.getParamClsName());
                mParameters[i] = GsonUtils.fromJson(param.getParamValue(), clazz);
            }
        } else {
            mParameters = new Object[0];
        }
        setMethod(requestBean);
        Object object = invokeMethod();
        // 对象封装成ResponseBean
        ResponseBean responseBean = new ResponseBean(object);
        // 将得到的结果序列化成字符串
        String json = GsonUtils.toJson(responseBean);
        LogUtils.i(getClass(), "makeResponse json: " +json);
        Response response = new Response(json);
        LogUtils.i(getClass(), "makeResponse response: " +response);
        return response;
    }

    /**
     * 方法调用：反射调用
     *
     * @return
     */
    protected abstract Object invokeMethod();

    /**
     * 填充Method
     *
     * @param requestBean
     */
    protected abstract void setMethod(RequestBean requestBean);
}
